#include "threadPool.h"
#include <stdio.h>
#include <string.h>

void write_log(const char *format, ...);

void _tidArr_init(_tidArr_t *tidArr, int workerNum)
{
    tidArr->_arr = (pthread_t *)calloc(workerNum, sizeof(pthread_t));
    tidArr->_worker_num = workerNum;
}

void *_threadFunc(void *threadPool)
{
    if (threadPool == NULL)
    {
        printf("input parameter error.\n");
        return NULL;
    }
    threadPool_t *pool = (threadPool_t *)threadPool;
    int netfd = -1;
    char buf[1024] = {0};
    while (1)
    {
        // deque task
        pthread_mutex_lock(&pool->_mutex);
        while (pool->_exitFlag == 0 && _taskQueue_is_empty(&pool->_q))
        {
            pthread_cond_wait(&pool->_cond, &pool->_mutex);
            /* printf("flag = %d\n", pool->_exitFlag); */
        }
        // exit
        if (pool->_exitFlag == 1)
        {
            printf("recv quit from parent proccess, worker exit.\n");
            close(netfd);
            pthread_mutex_unlock(&pool->_mutex);
            pthread_exit(NULL);
        }
        task_t *task = _taskQueue_front(&pool->_q);
        if (task == NULL)
        {
            perror("__taskQueue_front");
        }
        printf("client %d,msg = %s\n", task->_clientFd,
               task->_data); // cout all string in task->_data
        _taskQueue_deque(&pool->_q);
        pthread_mutex_unlock(&pool->_mutex);

        // task working
        // if(user){
        //     doTask(task, &user->_dirStack);
        //     free(task);
        // }

        // send tast return msg
        netfd = task->_clientFd;

        //===============test sendMsg====================
        // 确保 buf 不会溢出
        int ret =
            snprintf(buf, sizeof(buf), "client %d, return msg = %s result\n",
                     task->_clientFd, task->_data);
        // 如果 ret 大于或等于 buf 的大小，说明发生了截断
        if (ret >= sizeof(buf))
        {
            printf("Warning: Message truncated. Task message is too long for "
                   "buffer.\n");
            write_log("Warning: Message truncated. Task message is too long "
                      "for buffer.\n");
            buf[sizeof(buf) - 1] = '\0'; // 强制添加结束符，避免潜在溢出
        }
        sendMsg(netfd, buf);
        //===============test sendMsg====================
    }
    return NULL;
}

void threadPool_init(threadPool_t *pool, int workerNum)
{
    pthread_mutex_init(&pool->_mutex, NULL);
    pthread_cond_init(&pool->_cond, NULL);
    _taskQueue_init(&pool->_q);
    _tidArr_init(&pool->_tidArr, workerNum);
    pool->_exitFlag = 0;
    int res = 0;
    for (int i = 0; i < pool->_tidArr._worker_num; ++i)
    {
        res = pthread_create(&pool->_tidArr._arr[i], NULL, _threadFunc,
                             pool); // 直接传pool
        if (res == -1)
        {
            perror("pthread_create");
        }
        printf("worker %d start.\n", i);
    }
    printf("threadPool_init success.\n"); // test only
}
